<?php

namespace lvzmen\yii\cms\widgets\navs;

use yii\base\Widget;
use yii\bootstrap\Nav;

/**
 * A menu imitate the sidebar of https://docs.docker.com/get-started/
 *
 * @note It's depend on bootstrap;
 *
 * @example :
 * ```php
 * echo Tabs::widget([
 *     'items' => [
 *         [
 *             'label' => 'Home',
 *             'options' => ['class' => 'active'],
 *             'content' => "This is home tab;"
 *         ],
 *         [
 *             'label' => 'Profile',
 *             'content' => "This is profile tab;"
 *         ],
 *         [
 *             'label' => 'messages',
 *             'content' => "This is messages tab;"
 *         ],
 *         [
 *             'label' => 'settings',
 *             'content' => "This is settings tab;"
 *         ],
 *     ],
 * ]);
 * ```
 * @author chenzhiwei <chenzhiweiwk@qq.com>
 * @date   2021/08/31
 */
class Tabs extends Widget
{
    public $items = [];

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

        $this->items = array_map(function ($item) {
            $item["options"] = $item["options"] ?? [];
            $item["options"]["role"] = "presentation";
            $id = "tab_" . uniqid();
            $item["url"] = "#" . $id;
            $item["linkOptions"] = ["data-toggle" => "tab", "aria-controls" => $id];
            return $item;
        }, $this->items);
    }


    public function renderBody()
    {

        $html = "<div>";

        $html .= Nav::widget([
            "items" => $this->items,
            'options' => ['class' => 'nav-tabs'],
        ]);

        $html .= '<div class="tab-content">';
        foreach ($this->items as $item) {
            $item["options"] = $item["options"] ?? [];
            $class = $item["options"]["class"] ?? "";
            $active = strpos($class, "active") !== false ? "active" : "";
            $html .= '<div role="tabpanel" class="tab-pane ' . $active . '" id="' . $item['linkOptions']['aria-controls'] . '">';
            $html .= $item["content"] ?? "";
            $html .= '</div>';
        }
        $html .= '</div>';

        $html .= "</div>";


        return $html;

    }

    public function run()
    {
        return $this->renderBody();
    }
}
